﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Quartz.Impl;
using Quartz;

namespace ScenarioFramework.WorkflowEngine.Scheduler
{
    public class JobManager
    {
        #region Variables

        ISchedulerFactory schedFact = new StdSchedulerFactory();
        IScheduler sched;

        #endregion

        #region Constructor

        public JobManager()
        {
            // get a scheduler
            sched = schedFact.GetScheduler();
            sched.Start();

            
        }

        #endregion


        #region Methods

        public void Stop()
        {
            sched.Shutdown();
        }


        public void StartListener()
        {
            JobDetail jobDetail = new JobDetail("Listener", null, typeof(ScenarioFramework.WorkflowEngine.Scheduler.Jobs.ListenerJob));

            Settings.ListenerSection listenerConfig =
            (Settings.ListenerSection)System.Configuration.ConfigurationManager.GetSection("jobManager/listener");

            System.Console.Out.WriteLine (String.Format ("Start Listener polling time {0}",listenerConfig.PollingSeconds) );

            //TODO:  Leggere i parametri di configurazione.
            Trigger trigger = TriggerUtils.MakeSecondlyTrigger(listenerConfig.PollingSeconds);
            trigger.StartTimeUtc = DateTime.UtcNow;
            trigger.Name = "Listener";
            sched.ScheduleJob(jobDetail, trigger);
        }

        public void AddJob(string jobName, Type jobType, string triggerName, Trigger trigger, DateTime startDateTime  ) 
        {
            JobDetail jobDetail = new JobDetail(jobName, null, jobType);

            trigger.StartTimeUtc = startDateTime.ToUniversalTime();
            trigger.Name = triggerName;
            sched.ScheduleJob(jobDetail, trigger);
        }

        #endregion
    }
}
